package com.glela.report.service.amqp;

import java.util.Date;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.glela.cache.redis.RedisUtil;
import com.glela.report.mapper.QueueTasksMapper;
import com.glela.report.model.QueueTasks;

public class ReportDaliyAmqp {
	private static Logger logger = LoggerFactory.getLogger(ReportDaliyAmqp.class);

	private RedisUtil			redisUtil;
	private QueueTasksMapper	queueTasksMapper;

	public void onMessage(String msg) {
		QueueTasks checkQueueTasks = null;
		try {
			//转换消息
			if (StringUtils.isBlank(msg)) {
				logger.warn("报表-日报队列错误：消息内容为空[{}]", msg);
				return;
			}
			try {
				Map<Object, ?> parseObject = JSONObject.parseObject(msg, Map.class);
				if (MapUtils.isEmpty(parseObject)) {
					logger.warn("报表-日报队列错误：消息内容为空[{}]", msg);
					return;
				}
				int taskId = MapUtils.getIntValue(parseObject, "taskId", -1);
				if (taskId < 1) {
					logger.warn("报表-日报队列错误：任务ID非法[{}-{}]", msg, taskId);
					return;
				}
				//查询任务
				checkQueueTasks = queueTasksMapper.selectById(taskId);
				if (checkQueueTasks == null) {
					logger.warn("报表-日报队列错误：任务ID非法[{}-{}],不存在此记录", msg, taskId);
					return;
				}
				if (checkQueueTasks.getTaskStatus() != 0) {
					logger.warn("报表-日报队列错误：任务[{}-{}]状态不符[{}]", taskId, msg, checkQueueTasks.getTaskStatus());
					return;
				}
				DateTime nowDay = new DateTime();
				//更新状态为处理中
				updateTask(taskId, 1, "处理中", nowDay.toDate());
				//导出报表
				//更新为已处理

			} catch (Exception e) {
				logger.warn("报表-日报队列错误：解析消息失败：[{}]-{}", msg, e.getMessage(), e);
				return;
			}

		} catch (Exception e) {
			logger.error("报表-日报队列错误：处理消息失败：{}-{}", msg, e.getMessage(), e);
			if (checkQueueTasks != null) {//更新消息为失败
				updateTask(checkQueueTasks.getTask_id(), 3, StringUtils.substring(e.getMessage(), 0, 100), new Date());
			}

		} finally {}
	}

	private boolean updateTask(int taskId, int taskStatus, String taskResult, Date overTime) {
		return queueTasksMapper.updateStatusAndResult(taskId, taskStatus, taskResult, overTime) != 1;
	}

	public void setRedisUtil(RedisUtil redisUtil) {
		this.redisUtil = redisUtil;
	}

	public QueueTasksMapper getQueueTasksMapper() {
		return queueTasksMapper;
	}

	public void setQueueTasksMapper(QueueTasksMapper queueTasksMapper) {
		this.queueTasksMapper = queueTasksMapper;
	}

	public RedisUtil getRedisUtil() {
		return redisUtil;
	}

}
